package com.lkm.market2_0.m_imple.newDataUp;

import android.os.SystemClock;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.lkm.frame.P;
import com.lkm.frame.task.StopAble;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.DateHelp;
import com.lkm.javatool.JsonP;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.ServerTimeSync;
import com.lkm.javatool.URLHelp;
import com.lkm.javatool.lang.NameValueP;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.OrganizationInfo;
import com.lkm.market2_0.entity.StallEntity;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.help.RandomStringUtils;
import com.lkm.market2_0.m.dataUp.SZCalibrationInfo;
import com.lkm.market2_0.m.dataUp.SZHttpRequest;
import com.lkm.market2_0.m.dataUp.SZUpdateStatus;
import com.lkm.market2_0.m.dataUp.SZWeightInfo;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardValue;
import com.lkm.market2_0.m.steelyardstatus.StatusInfo;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;




public class NewSZApi {
    public static void main(String[] strings) {



        mainsubmitWeightInfo();
    }

    private static ServerTimeSync mServerTimeSync = new ServerTimeSync();

    protected static String Host = "https://fpms.chinaap.com/admin/trade";

    public static void setHost(String host) {
        Host = host;
    }

    public static String getHost() {
        return Host;
    }

    
    public static String mainKey = "F7AD4703F4520AFDB0216339";

    public static String appCode = "FPMSWS";



    public static String authenCode = "fpms_vender_zx";

    public static String password = "5ZtlpGaMjtaLAP35";


    
    public static String login_datakey = null;
    public static String login_authenCode = null;


    public static String getApiUrl(boolean isFileUploadForm) throws UnsupportedEncodingException {
        return URLHelp.appenParamsToUrl(Host, new NameValueP("executor", isFileUploadForm?"httpupload":"http"),
                new NameValueP("appCode", appCode)).replaceAll("\\+", "%20");
    }

    public static String calibrationInfo(SZCalibrationInfo szWeightInfo, StopAble sa, boolean isReSend) {
        String s = null;
        try {
            holdOnceLogin();

            Gson gson = new Gson();
            Map<String, String> params = gson.fromJson(gson.toJsonTree(szWeightInfo), new com.google.gson.reflect.TypeToken<Map<String, String>>() {
            }.getType());
            params.put("authenCode", login_authenCode);
            params.put("appCode", appCode);
//            P.p(new Gson().toJson(params));

            s = getString("deviceService", encrypt(login_datakey, "calibrationInfo"), params, mainKey,false, sa);

            System.out.println("=====sz提交标定：" + s);
            if (!checkLogin(s) && isReSend) {
                return calibrationInfo(szWeightInfo, sa, false);
            }


        } catch (Exception e) {

        }
        return s;
    }



    

    public static String updateStatus(String steelyardMac,SZUpdateStatus szWeightInfo, StopAble sa, boolean isReSend) {
        String s = null;
        try {
            holdOnceLogin();

            Gson gson = new Gson();
            Map<String, String> params = gson.fromJson(gson.toJsonTree(szWeightInfo), new com.google.gson.reflect.TypeToken<Map<String, String>>() {
            }.getType());
            params.put("authenCode", login_authenCode);
            params.put("appCode", appCode);
//            P.p(new Gson().toJson(params));

            s = getString("deviceService", encrypt(login_datakey, "updateStatus"), params, mainKey,false, sa);

            System.out.println("=====sz提交台秤状态：" + s);
            if (!checkLogin(s) && isReSend) {
                return updateStatus(steelyardMac,szWeightInfo, sa, false);
            }

            checkReg(steelyardMac,false, s);
        } catch (Exception e) {

        }
        return s;
    }


    

    public static String submitWeightImg(SZWeightImg[] szWeightImgs, StopAble sa, boolean isReSend) {
        String s = null;
        try {
            System.out.println("=====sz 开始提交图片"+ CollectionHelp.getSize(szWeightImgs));

            holdOnceLogin();

            Map<String, String> params = new HashMap<>();
            params.put("authenCode", login_authenCode);
            params.put("appCode", appCode);
//            params.put("dataImage", new Gson().toJson(szWeightImgs));
//            P.p(new Gson().toJson(params));
            for (int i = 0; i < szWeightImgs.length; i++) {

                szWeightImgs[i].orderTime = szWeightImgs[i].orderTime.replaceAll(" ","-").replaceAll(":","-");
            }



            s = getString("deviceService", encrypt(login_datakey, "uploadWeightImage"), params, mainKey,true, sa,new NameValueP[]{
                    new NameValueP("dataImage", new Gson().toJson(szWeightImgs))
            });

            System.out.println("=====sz提到图片：" + s);






        } catch (Exception e) {
            System.out.println("=====sz提到图片异常"+e.getMessage() );
        }
        return s;
    }
    

    public static String submitWeightInfo(SteelyardInfo steelyardInfo, SZWeightInfo[] szWeightInfo,  StopAble sa, boolean isReSend) {
        String s = null;
        try {
            System.out.println("=====sz 开始提交订单"+CollectionHelp.getSize(szWeightInfo));

            holdOnceLogin();



            Map<String, String> params = new HashMap<>();
            params.put("authenCode", login_authenCode);
            params.put("appCode", appCode);
            params.put("infoItems", new Gson().toJson(szWeightInfo));

            if(P.isDebug()){
                P.p("===sz === jsonSZ"+new Gson().toJson(params));
            }

            


            s = getString("deviceService", encrypt(login_datakey, "submitBatchWeightInfo"), params, mainKey,false, sa);

            System.out.println("=====sz提到订单：" + s);
            if (!checkLogin(s) && isReSend) {
                return submitWeightInfo(steelyardInfo,szWeightInfo, sa, false);
            }



            checkReg(steelyardInfo.getSteelyardMac(),false, s);

        } catch (Exception e) {

        }
        return s;
    }

    private static SteelyardStatusManagerModule mSteelyardStatusManagerModule;
    
    


      private static void checkReg(String steelyardMac,boolean isUpStateAPI,String s) {

        





        



        JsonP jsonP = new JsonP(s);

        String code = null;// jsonP.get("errorItems").get(0).get("errorMsg").getAsString("");

        boolean isNotReg = false;
        if(isUpStateAPI){
            code = jsonP.get("result").get("code").getAsString(null);
            if ("E000".equals(code)) {
                
                isNotReg = true;
            }
        }else {
            code = jsonP.get("errorItems").get(0).get("errorMsg").getAsString("");
            if (code.endsWith("无效.")) {
                isNotReg = true;
            }
        }

          if (mSteelyardStatusManagerModule == null)
           mSteelyardStatusManagerModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardStatusManagerModule.class);

          StatusInfo statusInfo = mSteelyardStatusManagerModule == null ? null : mSteelyardStatusManagerModule.getStatusInfoBySteelyardMac(steelyardMac);

          if (isNotReg) {
              if (statusInfo != null)
                  statusInfo.setSzStatus(1);
          } else {
              if (statusInfo != null)
                  statusInfo.setSzStatus(2);
          }


    }

    

    @Deprecated
    public static String calibrationInfo(SteelyardInfo steelyardInfo,SteelyardValue steelyardValue ,String offsetZeroAD,String weightAd,  StopAble sa) {
        String s = null;

        try {
            holdOnceLogin();

            Map<String, String> params = new HashMap<>();
            params.put("authenCode", login_authenCode);
            params.put("appCode", appCode);

            JsonObject deviceItem =new JsonObject();
            deviceItem.addProperty("deviceNo",steelyardInfo.getB_id());

            deviceItem.addProperty("deviceModel",steelyardInfo.deviceModel);


            deviceItem.addProperty("factoryName","广州市中兴电子衡器厂");
//            szWeightInfo.productionDate = steelyardInfo.deviceAge;
            deviceItem.addProperty("productionDate",steelyardInfo.deviceAge);

            deviceItem.addProperty("macAddr",steelyardInfo.getSteelyardMac());



            deviceItem.addProperty("calibrationWeight",steelyardValue.xzfmz/1000f);

            deviceItem.addProperty("zeroAd",offsetZeroAD);
            deviceItem.addProperty("weightAd",weightAd);

            deviceItem.addProperty("orderTime",DateHelp.DateFormatyyyy_MM_dd_HHmmss(Locale.getDefault()).format(new Date()));


            P.p(new Gson().toJson(params));

            s = getString("deviceService", encrypt(login_datakey, "calibrationInfo"), params, mainKey, true,sa);

            System.out.println("=====sz标定数据：" + s);

        } catch (Exception e) {

        }
        return s;
    }
    

    public static String reg(OrderEntity.GoodEntity goodEntity,SteelyardInfo steelyardInfo, StallEntity stallEntity, OrganizationInfo organizationInfo, StopAble sa) {
        String s = null;

        if (stallEntity == null) return "";

        try {
            holdOnceLogin();

            Map<String, String> params = new HashMap<>();
            params.put("authenCode", login_authenCode);
            params.put("appCode", appCode);

            if(organizationInfo!=null)
                params.put("marketId",organizationInfo.getNodeCode());
            if (stallEntity != null) {

                params.put("stallCode" , "" + stallEntity.getStallNo());
                params.put("businessEntity", stallEntity.businessentity);
                params.put("creditCode", stallEntity.creditcode);

                params.put("contacter",stallEntity.getName());
                params.put("telphone",stallEntity.getPhone());
                params.put("stallType", "" + stallEntity.getStart());
            }
//            System.out.println("==== " +new Gson().toJson(stallEntity));

            JsonObject deviceItem =new JsonObject();
//            szWeightInfo.deviceNo = steelyardInfo.getSteelyardMac();
            deviceItem.addProperty("deviceNo",steelyardInfo.getB_id());

            deviceItem.addProperty("deviceModel",steelyardInfo.deviceModel);
            deviceItem.addProperty("deviceName","物联溯源秤");

            deviceItem.addProperty("factoryName","广州市中兴电子衡器厂");
//            szWeightInfo.productionDate = steelyardInfo.deviceAge;
            deviceItem.addProperty("productionDate",steelyardInfo.deviceAge);






            deviceItem.addProperty("slope",goodEntity.kValue/10.0f);
            deviceItem.addProperty("initAd",goodEntity.zeroAD);
            deviceItem.addProperty("zeroAdStart",goodEntity.ad);
            deviceItem.addProperty("zeroAdEnd",goodEntity.ad);


            params.put("deviceItems", new Gson().toJson(new JsonObject[]{deviceItem}));
            P.p(new Gson().toJson(params));

            s = getString("deviceService", encrypt(login_datakey, "importStallInfo"), params, mainKey, true,sa);

            System.out.println("=====sz登记台秤：" + s);

        } catch (Exception e) {

        }
        return s;
    }
    

    public static boolean checkIsSuccess(String json){
        boolean isSuccess = new JsonP(json).get("result").get("success").getAsBoolean(false);
        return isSuccess;
    }
    
    

    private static boolean checkLogin(String s) {
        if(s==null)return !false;
        JsonP jsonP = new JsonP(s);
//        boolean isSuccess = jsonP.get("result").get("success").getAsBoolean(false);
        int type = jsonP.get("result").get("type").getAsInt(-1);
        String code = jsonP.get("result").get("code").getAsString(null);
        
        if ("OT-DATAKEY".equals(code)) {
            synchronized (NewSZApi.class) {
                login_datakey = null;
                login_authenCode = null;
                login(null);
            }
            return false;
        }
        return true;
    }

    

    private static synchronized void holdOnceLogin() {
        login(null);
    }

    

    private static synchronized boolean login(StopAble sa) {

        if (login_datakey != null || login_authenCode != null) {
            return true;
        }

        
        long requestTime = SystemClock.uptimeMillis();

        Map<String, String> params = new HashMap<>();
        params.put("authenCode", authenCode);
        params.put("password", password);

        System.out.println("=====sz登录开始");
        String s = getString("sign", "login", params, mainKey,false, sa);

        System.out.println("=====sz登录：" + s);
        if (s == null) {
            return false;
        }

        JsonP jsonP = new JsonP(s);
        boolean isSuccess = jsonP.get("result").get("success").getAsBoolean(false);

        if (!isSuccess) {
            return isSuccess;

        }
        login_datakey = jsonP.get("datakey").getAsString("");
        login_authenCode = jsonP.get("authenCode").getAsString("");




        String logintime = jsonP.get("logintime").getAsString("");

        try {
            long timeInMillis = DateHelp.parseStrToTimeInMillis(logintime);
            long curTime = SystemClock.uptimeMillis();
            mServerTimeSync.setNetLoadServerTime(curTime - requestTime, System.currentTimeMillis(), timeInMillis);


//                P.p("=====ServerTimeSync " + ServerTimeSync.getInstance().getServerCurTime());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    

    
    

    private static String getString(String service, String cmd, Map<String, String> params, String deskey,boolean isFileUploadForm,StopAble sa, NameValueP[] notencryptparams) {
        String s = null;
        try {
            String dataParam = getDataParam(service, cmd, params);
            dataParam = encrypt(deskey, dataParam);

            NameValueP[] valuePS = null;
            if(notencryptparams!=null){
                valuePS = new NameValueP[notencryptparams.length+1];
                for (int i = 0; i < notencryptparams.length; i++) {
                    valuePS[i] = notencryptparams[i];
                }
            }else{
                valuePS = new NameValueP[1];
            }
            valuePS[valuePS.length - 1] = new NameValueP("data", dataParam);




            s = SZHttpRequest.getString(
                    getApiUrl(isFileUploadForm),
                    valuePS
                    , isFileUploadForm,sa);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("=====sz " + e.getMessage());
        }
        return s;
    }
    private static String getString(String service, String cmd, Map<String, String> params, String deskey,boolean isFileUploadForm,StopAble sa) {
        return getString(service, cmd, params, deskey, isFileUploadForm, sa, null);
    }

    

    private static String getDataParam(String service, String cmd, Map<String, String> params) throws UnsupportedEncodingException {
        params.put("service", service);
        params.put("cmd", cmd);
        return URLHelp.parserUrlParamsToStr(params).replaceAll("\\+", "%20");

    }

    

    public static String encrypt(String key, String text) throws Exception {
        try {
            byte[] src = text.getBytes("utf-8");
            
            DESedeKeySpec spec = new DESedeKeySpec(key.getBytes("utf-8"));
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
            SecretKey secretKey = factory.generateSecret(spec);

            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] res = cipher.doFinal(src);
            return NumberHelp.bytesTohexDesc(res);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error");
        }
        return null;
    }

    

    
    public static void mainupdateStatus() {
        login(null);
        SZUpdateStatus szWeightInfo = new SZUpdateStatus();
        szWeightInfo.macAddr = "0033191200031";
        szWeightInfo.deviceNo = "0033191200031";
        szWeightInfo.deviceModel = "ACS-30";
        szWeightInfo.factoryName = "广州市中兴电子衡器厂";

        szWeightInfo.productionDate = "2019-01-01";

        szWeightInfo.userStatus = 0;

        szWeightInfo.stallCode = "";
        szWeightInfo.businessEntity = "A档1";
        szWeightInfo.creditCode = "1234567"; 
        updateStatus(szWeightInfo.macAddr,szWeightInfo, null, true);
    }


    
    public static void mainsubmitWeightInfo() {



        SZWeightInfo szWeightInfo = new SZWeightInfo();
        szWeightInfo.amounts = "20";
        szWeightInfo.macAddr = "003319120003";
        szWeightInfo.deviceNo = "003319120003";
        szWeightInfo.deviceModel = "ACS-30";
        szWeightInfo.orderNo = ServerTimeSync.getInstance().getServerCurTime() + RandomStringUtils.random(4, RandomStringUtils.azAZ90);
        szWeightInfo.factoryName = "广州市中兴电子衡器厂";

        szWeightInfo.productionDate = "2019-01-01";

        szWeightInfo.goodsCode = "22";
        szWeightInfo.goodsName = "白菜";

        szWeightInfo.orderTime = "2019-08-04 12:00:00";
        szWeightInfo.initAd = 100;
        szWeightInfo.zeroAd = 100;
        szWeightInfo.weightAd = 100;

        szWeightInfo.weight = "1";
        szWeightInfo.price = "1";

        szWeightInfo.stallCode = "33";
        szWeightInfo.businessEntity = "A档1";
        szWeightInfo.creditCode = "1234567"; 

        OrderEntity.GoodEntity goodEntity = new OrderEntity.GoodEntity("1","白菜",0,0,"",222,333,444,555,0, new OrderEntity.GoodEntityEx());

        submitWeightInfo(null,new SZWeightInfo[]{szWeightInfo},  null,true);
    }


    
    public static void mainreg(String[] strings) {

        login(null);

        SteelyardInfo steelyardInfo = new SteelyardInfo();
        steelyardInfo.setSteelyardMac("987654321111");
        steelyardInfo.deviceModel = "ACS-15";
        steelyardInfo.deviceAge = "2019-01-01";


        StallEntity stallEntity = new StallEntity();
        stallEntity.setId(223);
        stallEntity.businessentity = "A档口1323";
        stallEntity.creditcode = "91440101MA59HK2E9E";
        stallEntity.setName("刘先生");
        stallEntity.setPhone("123456789");
        OrganizationInfo organizationInfo = new OrganizationInfo();

        organizationInfo.setNodeCode("363");
        reg(new OrderEntity.GoodEntity("","",0,0,"",2222,3333,4444,555,0, new OrderEntity.GoodEntityEx()),
                steelyardInfo,stallEntity,organizationInfo, null);
    }

}
